<?php

namespace app\zyhsapi\model;

use app\common\cachemodel\ZlcrAstr;
use XznsTools\cache\zyhs\CacheManageZyhs;

class ZyhsConsultQuestion extends BaseCacheZyhs
{
    protected $table = 'good_wechat.zyhs_consult_question';

    protected $cacheModel = 'voice_consult.consult_question';

    /**
     * 获取 用户咨询问题信息
     * @param int $appType 1=>准有好事 2=>准了APP
     * @param int $uid
     * @return array|null
     * @throws \Exception
     */
    public function getUserConsultQuestion(int $appType, int $uid): ?array
    {
        $data = CacheManageZyhs::getInstance()->setCacheConfig($this->cacheModel, $appType . ':' . $uid)->getDataAndSet(function () use ($appType, $uid)
        {
            try
            {
                $time = time() - 86400;
                $data = $this->where(['app_type' => $appType, 'uid' => $uid])
                    ->where(['create_time' => ['>', $time]])
                    ->order('id desc')
                    ->limit(1)
                    ->field('id,app_type,uid,content,extend,create_time')
                    ->findOrFail()->toArray();

                return $data;
            }
            catch (\Exception $e)
            {
                return [''];
            }
        });

        if (array_filter($data))
        {
            $data = current($this->dataInit([$data]));
            if (!isset($data['create_time']) || time() - $data['create_time'] > 86400)
            {   // 删除 无效缓存
                CacheManageZyhs::getInstance()->setCacheConfig($this->cacheModel, $appType . ':' . $uid)->rmCache();
                return null;
            }
            return $data;
        } else
        {
            return null;
        }
    }

    /**
     * 保存 咨询问题 数据
     * @param array $data
     * @return int
     */
    public function saveData(array $data): int
    {
        try
        {
            if (isset($data['extend']) && is_array($data['extend']))
            {
                $data['extend'] = json_encode($data['extend']);
            }

            $id = $this->insertGetId($data);

            CacheManageZyhs::getInstance()->setCacheConfig($this->cacheModel, $data['app_type'] . ':' . $data['uid'])->rmCache();
            return (int)$id;
        }
        catch (\Exception $e)
        {
            \think\Log::write(__CLASS__ . ' => ' . __FUNCTION__ . '()异常：' . $e->getMessage() . '失败信息：' . $e->getFile() . ':' . $e->getLine(), 'error', true);
            return 0;
        }
    }

    /**
     * 更新 咨询问题 数据
     * @param int $id
     * @param int $appType 1=>准有好事 2=>准了APP
     * @param int $uid
     * @param array $data
     * @return bool
     */
    public function updateData(int $id, int $appType, int $uid, array $data): bool
    {
        try
        {
            if (isset($data['extend']) && is_array($data['extend']))
            {
                $data['extend'] = json_encode($data['extend']);
            }

            $this->where('id', $id)->update($data);

            CacheManageZyhs::getInstance()->setCacheConfig($this->cacheModel, $appType . ':' . $uid)->rmCache();
            return true;
        }
        catch (\Exception $e)
        {
            \think\Log::write(__CLASS__ . ' => ' . __FUNCTION__ . '()异常：' . $e->getMessage() . '失败信息：' . $e->getFile() . ':' . $e->getLine(), 'error', true);
            return false;
        }
    }

    /**
     * @param int $id
     * @param int $appType 1=>准有好事 2=>准了APP
     * @param int $uid
     * @param int $astrId
     * @param int $answerId
     * @return bool
     */
    public function editData(int $id, int $appType, int $uid, int $astrId, int $answerId)
    {
        try
        {
            $extend = $this->where('id', $id)->value('extend');
            if (!$extend)
            {
                return true;
            }
            $extend = json_decode($extend, true);
            $isUpdate = false;
            foreach ($extend['send_astro'] as $key => $item)
            {
                if ((int)$item['astr_id'] === $astrId)
                {
                    $extend['send_astro'][$key]['answer_id'] = $answerId;
                    $isUpdate = true;
                    break;
                }
            }
            if ($isUpdate)
            {   // 更新数据
                $this->updateData($id, $appType, $uid, ['extend' => json_encode($extend, JSON_UNESCAPED_UNICODE)]);
            }
        }
        catch (\Exception $e)
        {
            \think\Log::write(__CLASS__ . ' => ' . __FUNCTION__ . '()异常：' . $e->getMessage() . '失败信息：' . $e->getFile() . ':' . $e->getLine(), 'error', true);
            return false;
        }

        return true;
    }

    /**
     * @param array $ids
     * @param array|null $type
     * @param string $sortType
     * @return array
     */
    public function getInfoByIdsInData($ids, $type, $sortType): array
    {
        if ($ids)
        {   // 获取未删除 的数据
            $where = ['uid' => ['in', $ids]];
        } else
        {   // 获取指定pid  未删除 且 未隐藏的数据
            $where = ['uid' => $type[0]];
        }
        $field = 'id,uid,content,extend,create_time';
        try
        {
            $time = time() - 86400;
            $data = $this
                ->field($field)
                ->where($where)
                ->where(['create_time' => ['>', $time]])
                ->order('id desc')
                ->limit(1)
                ->column($field, 'uid');
        }
        catch (\Exception $e)
        {
            $data = [];
        }
        return $data;
    }

    public function batchGetInfoByIds($cids, $field = []): array
    {
        $resData = parent::batchGetInfoByIds($cids, $field);

        return $this->dataInit($resData);
    }

    /**
     * 数据初始化
     * @param array $data
     * @return array
     */
    public function dataInit(array $data): array
    {
        foreach ($data as $index => $itemData)
        {
            $data[$index] = arrayKeyData2int($itemData, ['id', 'uid', 'create_time']);

            if (isset($itemData['extend']))
            {
                $data[$index]['extend'] = $itemData['extend'] ? json_decode($itemData['extend'], true) : [];
            }
        }

        return $data;
    }

    /**
     * 重组 咨询问题信息
     * @param $data
     * @return array
     */
    public function resetConsultQuestion($data): array
    {
        if ($data)
        {
            $zlcrAstrModel = new ZlcrAstr();
            $astrList = [];
            foreach ($data['extend']['send_astro'] as $datum)
            {
                if (!$datum['answer_id'])
                {
                    continue;
                }
                $astrInfo = $zlcrAstrModel->getInfoById($datum['astr_id'], ['avatar', 'nickname']);
                $astrList[] = [
                    'name' => $astrInfo['nickname'],
                    'avatar' => $astrInfo['avatar'],
                    'is_read' => $datum['is_read'],
                    'astr_id' => $datum['astr_id'],
                ];
            }

            $title2 = '问题已提交，请耐心等待咨询师回复…';
            if ($astrList)
            {
                $title2 = '选择你心仪的咨询师去完成咨询服务吧～';
            } else
            {
                $astrList[] = [
                    'name' => '等待中…',
                    'avatar' => '/test/rtc_consult/rtc_default_avatar.png',
                    'is_read' => 1,
                    'astr_id' => 0,
                ];
                if (time() - $data['create_time'] > 600)
                {
                    $title2 = '当前咨询量过大，请耐心等待…';
                }
                $refresh = !(count($astrList) >= 5);
            }
            $info = [
                'id' => $data['id'],
                'title1' => '我的咨询',
                'title2' => $title2,
                'content' => $data['content'],
                'astro_list' => $astrList,
            ];
        }

        return [
            'tips' => '提交你的问题，我们将会为你匹配空闲的咨询师回复你，针对你的问题推荐咨询方案。',
            'info' => $info ?? null,
            'refresh' => $refresh ?? false,
        ];
    }

    /**
     * 获取 向咨询师 发送咨询次数
     */
    public function getSendAstroQuestionNum()
    {
        return CacheManageZyhs::getInstance()->setCacheConfig($this->cacheModel)
            ->getDataAndSet(function ()
            {
                try
                {
                    $astroList = $this->table('wechat_backup_07_18_14_43_00.zlcr3_consult_account')->where('consult_status', 1)->column('astr_id');
                    $data = [];
                    foreach ($astroList as $astrId)
                    {
                        $data[$astrId] = 0;
                    }
                    return $data;
                }
                catch (\Exception $e)
                {
                    \think\Log::write(__CLASS__ . ' => ' . __FUNCTION__ . '()异常：' . $e->getMessage() . '失败信息：' . $e->getFile() . ':' . $e->getLine(), 'error', true);
                    $data = [];
                }
                return $data;
            }, [], 'astro_send_num');
    }

    /**
     * 更新 向咨询师 发送咨询次数
     * @param array $data
     * @return void
     * @throws \Exception
     */
    public function setSendAstroQuestionNum(array $data)
    {
        CacheManageZyhs::getInstance()->setCacheConfig($this->cacheModel)->setCache($data, 'astro_send_num', true);
    }

    /**
     * 获取 发送问题 咨询师IDS
     * @param array $astroHotData
     * @param int $num
     * @return array
     * @throws \Exception
     */
    public function getSendQuestionAstrIds(array $astroHotData, int $num)
    {
        $sendQuestionNumData = $this->getSendAstroQuestionNum();
        $astrIdsData = [];
        $astrIdsData2 = [];
        foreach ($sendQuestionNumData as $astrId => $sendNum)
        {
            if (isset($astroHotData[$astrId]))
            {
                if ($sendNum < 5)
                {
                    $astrIdsData[$astrId] = $astroHotData[$astrId];
                } else
                {
                    $astrIdsData2[$astrId] = $astroHotData[$astrId];
                }
            }
        }
        asort($astrIdsData);
        asort($astrIdsData2);
        $resAstrIds = [];
        $n = 0;
        foreach ($astrIdsData as $astrId => $hot)
        {
            if ($n >= $num)
            {
                break;
            }
            $resAstrIds[] = $astrId;
            $n++;
            $sendQuestionNumData[$astrId] = $sendQuestionNumData[$astrId] + 1;
        }
        if ($n < $num)
        {   // 咨询师数量
            foreach ($astrIdsData2 as $astrId => $hot)
            {
                if ($n >= $num)
                {
                    break;
                }
                $resAstrIds[] = $astrId;
                $n++;
                $sendQuestionNumData[$astrId] = $sendQuestionNumData[$astrId] + 1;
            }
        }

        $sendQuesNumData1 = [];
        $isDec = true;
        foreach ($sendQuestionNumData as $astrId => $sendNum)
        {
            if ($sendNum < 5)
            {
                $isDec = false;
                break;
            }
            $sendQuesNumData1[$astrId] = $sendNum - 5;
        }
        if ($isDec)
        {
            $sendQuestionNumData = $sendQuesNumData1;
        }

        // 更新 向咨询师发送咨询问题 次数
        $this->setSendAstroQuestionNum($sendQuestionNumData);
        return $resAstrIds;
    }
}